package com.action.mvc.auth.context;

import com.action.mvc.auth.entity.Function;
import com.action.mvc.auth.entity.Role;
import com.action.mvc.auth.service.FunctionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Wuxiang on 2017/4/24.
 * 适用范围：1.单机应用 2.不涉及修改
 */
@Service
public class NativeCache {
    private Map<Long, Function> functionMap = new HashMap<>();
    private Map<Long, List<Role>> userRoleMap = new HashMap<>();

    @Autowired
    private FunctionService functionService;

    @PostConstruct
    public void init() {
        List<Function> functions = functionService.getALlFunctions();
        functions.forEach(function -> {
            functionMap.put(function.getId(), function);
        });
    }

    public List<Function> getFunctions() {
        if (functionMap.isEmpty()) {
            init();
        }
        return new ArrayList<Function>(functionMap.values());
    }

    public void addFunction(Function function) {
        functionMap.put(function.getId(), function);
    }

    public void replaceFunction(Function function){
        if(functionMap.containsKey(function.getId())){
            functionMap.remove(function.getId());
            functionMap.put(function.getId(), function);
        }
    }
    public void removeFunction(Long functionId){
        if(functionMap.containsKey(functionId)){
            functionMap.remove(functionId);
        }
    }

    public void setRoles(Long userId , List<Role>Roles){
        userRoleMap.put(userId, Roles);
    }

    public List<Role> getRoles(Long userId){
        return userRoleMap.get(userId);
    }

    public Function getFunction(Long id){
        return functionMap.get(id);
    }
}
